package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/7/6 23:49
 * @desciption
 */
@Service
public class CommentRepayServiceImpl implements ICommentRepayService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult save(CommentRepaySaveDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApCommentRepay apCommentRepay = new ApCommentRepay();

        if (user.getUserId() == 0){
            // 以游客身份回复
            apCommentRepay.setUserId(user.getUserId());
            apCommentRepay.setUserName("游客");

        }else {
            apCommentRepay.setUserId(user.getUserId());
            ResponseResult<ApUser> apUserResponseResult = userFeign.getById(user.getUserId());
            ApUser apUser = apUserResponseResult.getData();
            apCommentRepay.setUserName(apUser.getName());
        }

        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());

        // 保存评论
        mongoTemplate.save(apCommentRepay);

       // 将评论的回复数量加1
        Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));

        Update update = new Update();
        update.inc("repay",1);
        mongoTemplate.updateFirst(query,update, ApComment.class);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult load(CommentRepayDto dto) {

        User user = UserThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto.getSize() == null){
            dto.setSize(10);
        }
        // 根据评论id查询回复列表
        Query query = new Query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        // 按照创建时间倒序排列
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        // 分页判断数据小于前端传递的最小时间
        // 每页默认显示10条评论数据
        query.limit(dto.getSize());
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(query, ApCommentRepay.class);

        List<ApCommentRepayVo> commentRepayVoList = new ArrayList<>();
        for (ApCommentRepay commentRepay : commentRepayList) {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(commentRepay,apCommentRepayVo);
            if (redisTemplate.hasKey("commentRepay_like_" + user.getUserId() + "_" + commentRepay.getId())){
                apCommentRepayVo.setOperation(0); // 代表已点赞
            }else {
                apCommentRepayVo.setOperation(1); // 代表未点赞
            }
            commentRepayVoList.add(apCommentRepayVo);
        }
        return ResponseResult.okResult(commentRepayVoList);
    }

    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {

        User user = UserThreadLocalUtil.get();
        if(user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto.getOperation() == 0) { // 0：点赞
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setUserId(user.getUserId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);

            // 修改当前回复的点赞数
            Query query = new Query(Criteria.where("_id").is(dto.getCommentRepayId()));
            Update update = new Update();
            update.inc("likes",1);
            mongoTemplate.updateFirst(query,update,ApCommentRepay.class);

            // 记录到redis中: 记录当前登录人是否对该回复点赞
            // key要体现出 谁对哪个回复点赞
            redisTemplate.boundValueOps("commentRepay_like_" + user.getUserId() + "_" + dto.getCommentRepayId()).set("");


        }else { // 1：取消点赞
            // 把当前用户的点赞数据删除
            mongoTemplate.remove(new Query(Criteria.where("userId").is(user.getUserId()).and("commentRepayId").is(dto.getCommentRepayId())),ApCommentRepayLike.class);
            Query query = new Query(Criteria.where("_id").is(dto.getCommentRepayId()));

            Update update = new Update();
            update.inc("likes",-1);
            mongoTemplate.updateFirst(query,update,ApCommentRepay.class);
            // 取消点赞,删除redis中的标记
            redisTemplate.delete("commentRepay_like_" + user.getUserId() + "_" + dto.getCommentRepayId());
        }

        return ResponseResult.okResult();
    }
}
